package policy_do

import (
	"encoding/json"
	"gitee.com/Hu-Lyndon/cron-go"
	"time"
)

func NewDefaultPolicy(id int, name string, policys string, enable int) (policy *internalPolicy, err error) {
	var policyInfos []PolicyInfo

	err = json.Unmarshal([]byte(policys), &policyInfos)
	if err != nil {
		return
	}

	policy = &internalPolicy{
		id:          id,
		name:        name,
		policyInfos: policyInfos,
		enable:      enable,
	}
	return
}

type Policy interface {
	PolicyId() int
	PolicyName() string
	Policy() interface{}
	Effective() (int, error)
	Enable() int
}

type internalPolicy struct {
	id          int
	name        string
	policyInfos []PolicyInfo
	enable      int
}

type PolicyInfo struct {
	CronExpr   string `json:"cronExpr"`
	Concurrent int    `json:"concurrent"`
}

func (i *internalPolicy) PolicyId() int {
	return i.id
}

func (i *internalPolicy) PolicyName() string {
	return i.name
}

func (i *internalPolicy) Policy() interface{} {
	return i.policyInfos
}

func (i *internalPolicy) Enable() int {
	return i.enable
}

// 判断策略和当前时间比对是否有效
func (i *internalPolicy) Effective() (int, error) {
	for _, policyInfo := range i.policyInfos {
		policyExpr, err := cron.NewCron(policyInfo.CronExpr)
		// 设置的cron表达式有误
		if err != nil {
			return 0, err
		}
		// 如果有效，则返回cron表达式有效
		if policyExpr.Match(time.Now()) {
			return policyInfo.Concurrent, nil
		}
	}
	return 0, nil
}
